package com.zyz.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyz.common.pojo.Result;
import com.zyz.common.utils.JWTUtils;
import com.zyz.gateway.properties.AuthWhiteName;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthWhiteName authWhiteName;

//    private final List<String> whiteNames = List.of("/user/login","user/register");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 配置白名单
        ServerHttpRequest request = exchange.getRequest();
        String urlStr = request.getURI().getPath();
//        log.info("authWhiteName: {}",authWhiteName.getUrl());
        if (match(urlStr,authWhiteName)) {
            return chain.filter(exchange);  // 放行
        }
        // 从header中拿到token
        String userToken = request.getHeaders().getFirst("user_token");
        log.info("从header中拿到userToken：{}",userToken);

        if (!StringUtils.hasLength(userToken)) {
            // TODO;
            return unauthorizedResponse(exchange,"令牌不存在");
        }
        // 验证用户token
        Claims claims = JWTUtils.parseJWT(userToken);
        if (claims == null) {
            // TODO
            log.info("令牌校验失败");
            return unauthorizedResponse(exchange,"令牌过期或者不合法");
        }
        return chain.filter(exchange);
    }

    private boolean match(String urlStr, AuthWhiteName authWhiteName) {
        List<String> whiteUrls = authWhiteName.getUrl();
//        log.info("whiteUrls: " + whiteUrls.toString());
        if (whiteUrls == null || whiteUrls.isEmpty()) {
            return false;
        }
        if (whiteUrls.contains(urlStr)) {
            return true;
        }
        return false;
    }
    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String errMsg) {
        ServerHttpResponse response = exchange.getResponse();
        String url = exchange.getRequest().getURI().getPath();
        log.info("[用户认证失败] url: {}",url);

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE,"application/json");
        Result result = Result.fail(errMsg);
        // 把错误信息转换成json
        DataBuffer dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        // order值越小  优先级越高
        return Ordered.LOWEST_PRECEDENCE;
    }
}
